<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { Loader } from '@vben/icons';
import * as pdfjsLib from 'pdfjs-dist';
import { getImgUrl } from "#/utils/getImgUrl"
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  '#/utils/pdf.worker.min.js',
  import.meta.url,
).href;
const refSrc = ref()
const imgRef = ref()
const imgLoaded = ref(false)

const props = defineProps({
  certificate: {
    type: String,
    default: () => { }
  }
})
// file 是 Blob 或 ArrayBuffer
async function pdfToThumbnail(file: any) {
  // 1. 读取PDF
  const pdf = await pdfjsLib.getDocument({ data: file }).promise
  // 2. 获取首页
  const page = await pdf.getPage(1)
  // 3. 创建canvas
  const viewport = page.getViewport({ scale: 2 }) // 缩略图比例
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = viewport.width
  canvas.height = viewport.height
  // 4. 渲染到canvas
  await page.render({ canvasContext: context, viewport } as any).promise
  // 5. 转为图片
  return canvas.toDataURL('image/png')
}

// 用法示例
const handlePdfBlob = async (blob: any) => {
  refSrc.value = await pdfToThumbnail(blob)
  imgLoaded.value = false
  emit('loadSuccess', true)
  // imgUrl 可直接用于 <img :src="imgUrl" />
}

const loadImage = async (path: any) => {
  imgLoaded.value = true
  const src = await getImgUrl(path) as any
  handlePdfBlob(src)
}

const handlePreview = () => {
  if (imgRef.value) {
    imgRef.value!.showPreview()
  }
}

onMounted(() => {
  if (props.certificate) {
    loadImage(props.certificate)
  }
})
const emit = defineEmits(['loadSuccess'])
defineExpose({
  handlePreview
})
</script>
<template>
  <section class="flex flex-col h-full">
    <div v-if="imgLoaded" class="w-full h-full flex items-center justify-center">
      <Loader class="circular"></Loader>
    </div>
    <el-image class="w-full h-auto" fit="cover" v-else :src="refSrc" :preview-src-list="[refSrc]"
      ref="imgRef"></el-image>
  </section>
</template>
<style scoped>
.circular {
  margin-right: 6px;
  width: 18px;
  height: 18px;
  animation: loading-rotate 2s linear infinite;
}
</style>
